package com.diandian.backend.client.service;

import com.diandian.backend.client.domain.ClientInfo;
import com.diandian.backend.client.dto.*;
import com.diandian.backend.client.mapper.ClientInfoMapper;
import com.diandian.backend.client.resp.*;
import com.diandian.base.boot.starter.exception.DefaultException;
import com.diandian.base.boot.starter.response.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ClientInfoService {

    @Autowired
    private ClientPermissionService clientPermissionService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private ClientInfoMapper clientInfoMapper;

    public ClientInfoDetailResp getDetail(ClientInfoDetailParamDTO param) {

        ClientInfo dbData = clientInfoMapper.getDetail(param);
        if(dbData == null){
            return null;
        }

        ClientInfoDetailResp result = new ClientInfoDetailResp();
        result.setId(dbData.getId());
        result.setClientId(dbData.getClientId());
        result.setClientKey(dbData.getClientKey());
        result.setClientSecret(dbData.getClientSecret());
        result.setRemark(dbData.getRemark());
        result.setStatus(dbData.getStatus());
        result.setStartTime(dbData.getStartTime());
        result.setEndTime(dbData.getEndTime());
        result.setCreateTime(dbData.getCreateTime());
        result.setCreateUserId(dbData.getCreateUserId());
        result.setCreateUserName(dbData.getCreateUserName());
        result.setUpdateTime(dbData.getUpdateTime());
        result.setUpdateUserId(dbData.getUpdateUserId());
        result.setUpdateUserName(dbData.getUpdateUserName());
        result.setDel(dbData.getDel());
        return result;
    }

    public List<String> getAllClientId() {
        List<String> allClientIdList = clientInfoMapper.getAllClientId();
        return allClientIdList == null ? new ArrayList<>() : allClientIdList;
    }

    public PageResult page(ClientClientInfoPageParamDTO requestDTO){

        requestDTO.check();
        int pageNum = requestDTO.getPageNum();
        int pageSize = requestDTO.getPageSize();

        // 查询总数
        int totalCount = clientInfoMapper.getCount(requestDTO);

        // 查询数据集合
        List<ClientInfo> dataList = clientInfoMapper.getPage(requestDTO, requestDTO.getPageSize(), (requestDTO.getPageNum() - 1) * requestDTO.getPageSize());

        // 组装数据
        List<ClientClientInfoPageResp> respList = new ArrayList<>();
        if(dataList != null && dataList.size() > 0){
            dataList.stream().forEach( x ->{
                ClientClientInfoPageResp item = new ClientClientInfoPageResp();
                item.setId(x.getId());
                item.setClientId(x.getClientId());
                item.setClientKey(x.getClientKey());
                item.setClientSecret(x.getClientSecret());
                item.setRemark(x.getRemark());
                item.setStatus(x.getStatus());
                item.setStartTime(x.getStartTime());
                item.setEndTime(x.getEndTime());
                item.setCreateTime(x.getCreateTime());
                item.setCreateUserId(x.getCreateUserId());
                item.setCreateUserName(x.getCreateUserName());
                item.setUpdateTime(x.getUpdateTime());
                item.setUpdateUserId(x.getUpdateUserId());
                item.setUpdateUserName(x.getUpdateUserName());
                item.setDel(x.getDel());
                respList.add(item);
            });
        }

        return new PageResult(pageNum, pageSize, totalCount, respList);
    }

    public PageResult functionSettingPage(int pageNum, int pageSize, String clientId){

        // 查询所有的功能清单
        ClientPermissionPageParamDTO permissionPageParamDTO = new ClientPermissionPageParamDTO();
        permissionPageParamDTO.setPageNum(pageNum);
        permissionPageParamDTO.setPageSize(pageSize);
        PageResult permissionPageResult = permissionService.page(permissionPageParamDTO);
        if(permissionPageResult == null || permissionPageResult.total == 0){
            return permissionPageResult;
        }

        // 获取所有权限记录
        List<ClientPermissionPageResp> permissionList = permissionPageResult.getDataList();

        // 获取当前客户端的所有权限
        List<String> hasPermissionKeyList = clientPermissionService.getPermissions(clientId);
        if(hasPermissionKeyList == null){
            hasPermissionKeyList = new ArrayList<>();
        }

        // 组装返回结果
        List<ClientFunctionSettingPageResp> resultList = new ArrayList<>();
        for (int i = 0; i < permissionList.size(); i++) {
            String permissionKey = permissionList.get(i).getPermissionKey();

            ClientFunctionSettingPageResp item = new ClientFunctionSettingPageResp();
            item.setId(permissionList.get(i).getId());
            item.setPermissionGroup(permissionList.get(i).getPermissionGroup());
            item.setPermissionKey(permissionKey);
            item.setPermissionName(permissionList.get(i).getPermissionName());
            item.setOwnFlag(hasPermissionKeyList.contains(permissionKey));
            resultList.add(item);
        }

        return new PageResult(pageNum, pageSize, permissionPageResult.getTotal(), resultList);
    }

    public List<ClientClientInfoListResp> getList(ClientClientInfoListParamDTO requestDTO){

        // 查询数据集合
        List<ClientInfo> dataList = clientInfoMapper.getList(requestDTO);

        // 组装数据
        List<ClientClientInfoListResp> respList = new ArrayList<>();
        if(dataList != null && dataList.size() > 0){
            dataList.stream().forEach( x ->{
                ClientClientInfoListResp item = new ClientClientInfoListResp();
                item.setId(x.getId());
                item.setClientId(x.getClientId());
                item.setClientKey(x.getClientKey());
                item.setClientSecret(x.getClientSecret());
                item.setRemark(x.getRemark());
                item.setStatus(x.getStatus());
                item.setStartTime(x.getStartTime());
                item.setEndTime(x.getEndTime());
                item.setCreateTime(x.getCreateTime());
                item.setCreateUserId(x.getCreateUserId());
                item.setCreateUserName(x.getCreateUserName());
                item.setUpdateTime(x.getUpdateTime());
                item.setUpdateUserId(x.getUpdateUserId());
                item.setUpdateUserName(x.getUpdateUserName());
                item.setDel(x.getDel());
                respList.add(item);
            });
        }

        return respList;
    }

    public ClientInfoDetailResp updateById(ClientClientInfoUpdateByIdParamDTO param) {

        param.check();

        ClientInfoDetailParamDTO queryDetailDTO = new ClientInfoDetailParamDTO();
        queryDetailDTO.setId(param.getId());
        ClientInfoDetailResp dbData = getDetail(queryDetailDTO);
        if(dbData == null){
            throw new DefaultException("更新的记录不存在");
        }
        if(!dbData.getClientId().equals(param.getClientId())){
            throw new DefaultException("客户端id不允许修改");
        }
        if(!dbData.getClientKey().equals(param.getClientKey())){
            throw new DefaultException("客户端key不允许修改");
        }

        clientInfoMapper.updateById(param);
        return dbData;

    }

    @Transactional(rollbackFor = Exception.class)
    public ClientInfoDetailResp deleteById(ClientClientInfoDeleteByIdParamDTO paramDTO) {
        paramDTO.check();

        ClientInfoDetailParamDTO queryDetailDTO = new ClientInfoDetailParamDTO();
        queryDetailDTO.setId(paramDTO.getId());
        ClientInfoDetailResp clientInfoDetailResp = getDetail(queryDetailDTO);
        if(clientInfoDetailResp == null){
            throw new DefaultException("删除的记录不存在");
        }

        // 删除主数据
        clientInfoMapper.deleteById(paramDTO);

        // 删除关联数据
        clientPermissionService.deleteByClientId(clientInfoDetailResp.getClientId());

        return clientInfoDetailResp;
    }

    public void add(ClientClientInfoAddParamDTO param) {

        param.check();

        // clientId不允许重复
        ClientInfoDetailParamDTO queryDetailDTO = new ClientInfoDetailParamDTO();
        queryDetailDTO.setClientId(param.getClientId());
        ClientInfo dbData = clientInfoMapper.getDetail(queryDetailDTO);
        if(dbData != null){
            throw new DefaultException("客户端id不允许重复");
        }
        // clientKey不允许重复
        queryDetailDTO = new ClientInfoDetailParamDTO();
        queryDetailDTO.setClientKey(param.getClientKey());
        dbData = clientInfoMapper.getDetail(queryDetailDTO);
        if(dbData != null){
            throw new DefaultException("客户端key不允许重复");
        }

        param.setDel(0);
        param.setCreateTime(new Date());

        clientInfoMapper.add(param);
    }
}
